package com.fubowen.lepton.ui.search.recycler

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.fubowen.lepton.R

class SearchAdapter : ListAdapter<Search, SearchAdapter.SearchViewHolder>(diffCallback) {

    private var onClickListener: OnClickListener? = null

    fun setOnClickListener(listener: OnClickListener) {
        this.onClickListener = listener
    }

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): SearchViewHolder {

        val layoutInflater = LayoutInflater.from(viewGroup.context)
        val view = layoutInflater.inflate(R.layout.fragment_search_list_item, viewGroup, false)
        return SearchViewHolder(view, this.onClickListener)
    }

    override fun onBindViewHolder(viewHolder: SearchViewHolder, position: Int) {
        viewHolder.bind(getItem(position))
    }

    companion object {

        val diffCallback = object : DiffUtil.ItemCallback<Search>() {

            override fun areItemsTheSame(oldItem: Search, newItem: Search): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: Search, newItem: Search): Boolean {
                return oldItem.id == newItem.id
            }
        }
    }

    interface OnClickListener {
        fun onItemClick(view: View?)
    }

    inner class SearchViewHolder(
        view: View,
        listener: OnClickListener?
    ) : RecyclerView.ViewHolder(view) {

        private val title: TextView
        private var description: TextView
        private var onClickListener = listener

        init {
            title = view.findViewById(R.id.bookmark_item_title)
            description = view.findViewById(R.id.bookmark_item_url)
            title.setOnClickListener { onClickListener?.onItemClick(view) }
        }

        fun bind(item: Search?) {
            title.text = item?.title
            description.text = item?.description
        }
    }
}
